<template>
  <div class="login">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <input v-model="username" placeholder="用户名" required />
      <input v-model="password" type="password" placeholder="密码" required />
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    // src/views/Login.vue
handleLogin() {
  const role = this.username === 'admin' ? 'admin' : 'student';
  localStorage.setItem('user', JSON.stringify({ role }));

  // 动态添加路由
  const routes = [
    {
      path: '/public-activities',
      name: 'public-activities',
      component: () => import('./PublicActivities.vue')
    },
    {
      path: '/public-activities/:id',
      name: 'activity-details',
      component: () => import('./ActivityDetails.vue'),
      props: true
    }
  ];

  if (role === 'admin') {
    routes.push({
      path: '/activity-management',
      name: 'activity-management',
      component: () => import('./ActivityManagement.vue'),
      beforeEnter: (to, from, next) => {
        const user = JSON.parse(localStorage.getItem('user'));
        user?.role === 'admin' ? next() : (alert('无权限访问'), next('/'));
      }
    });
  }

  // 使用 addRoutes 方法一次性添加所有动态路由
  this.$router.addRoutes(routes);

  // 跳转到首页
  this.$router.push('/');
}
  }
}
</script>